package com.mfkj.update

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.ThreadUtils
import com.google.android.material.snackbar.Snackbar
import com.hjq.toast.ToastUtils
import com.tencent.mmkv.MMKV
import me.reezy.cosmo.update.UpdateManager
import java.io.File
import java.lang.reflect.Field
import kotlin.reflect.KProperty


/**
 * 吐司
 */
/**
 * 吐司
 */
fun toast(toast: String) {
//    Toast.makeText(Utils.getApp(), toast, Toast.LENGTH_SHORT).show()
    ToastUtils.show(toast)
//    ToastUtils.showShort(toast)
}

fun toast(toast: Int) {
    ToastUtils.show(toast)
//    ToastUtils.showShort(toast)

//    Toast.makeText(Utils.getApp(), toast, Toast.LENGTH_SHORT).show()
}

fun getAuthority(): String {
    return "${AppUtils.getAppPackageName()}.fileprovider"
}


//修复WebView崩溃问题
@SuppressLint("PrivateApi", "DiscouragedPrivateApi")
fun hookWebView() {
    try {
        //反射调用API 解决系统级别WebView执行不了的问题
        val factoryClass = Class.forName("android.webkit.WebViewFactory")
        val field: Field = factoryClass.getDeclaredField("sProviderInstance")
        field.isAccessible = true
        var sProviderInstance = field.get(null)
        if (sProviderInstance != null) return
        val getProviderClassMethod = when {
            Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1 -> {
                factoryClass.getDeclaredMethod("getProviderClass")
            }
            Build.VERSION.SDK_INT == Build.VERSION_CODES.N -> {
                factoryClass.getDeclaredMethod("getFactoryClass")
            }
            else -> {
                null
            }
        } ?: return
        getProviderClassMethod.isAccessible = true
        val providerClass = getProviderClassMethod.invoke(factoryClass) as Class<*>
        val delegateClass = Class.forName("android.webkit.WebViewDelegate")
        providerClass.getConstructor(delegateClass)?.let {
            it.isAccessible = true
            val declaredConstructor = delegateClass.getDeclaredConstructor()
            declaredConstructor.isAccessible = true
            sProviderInstance = it.newInstance(declaredConstructor.newInstance())
            field.set("sProviderInstance", sProviderInstance)
        }
    } catch (e: Throwable) {
        e.printStackTrace()
    }


}

fun Context.snackBarToast(view: View, strId: Int) {
    Snackbar.make(view, getString(strId), Snackbar.LENGTH_SHORT).show()
}

fun Any?.runOnUiThread(method: () -> Unit) {
    ThreadUtils.runOnUiThread {
        try {
            method.invoke()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}


fun Any?.runOnUiThreadDelayed(delayMillis: Long, method: () -> Unit) {
    ThreadUtils.runOnUiThreadDelayed({
        method.invoke()
    }, delayMillis)
}

/**
 * Return the application's version code.
 *
 * @param packageName The name of the package.
 * @return the application's version code
 */
fun getAppVersionCode(): Int {
    return AppUtils.getAppVersionCode()
}

/**
 * List<*>
 * 判断空或没数据
 */
fun List<*>?.isNullOrEmpty(): Boolean {
    return this == null || this.isEmpty()
}

/**
 * 任意类型
 * 判断是空
 */
fun Any?.isNull(): Boolean {
    return this == null
}

/**
 * 任意类型
 * 判断不是空
 */
fun Any?.isNotNull(): Boolean {
    return this != null
}

/**
 * String
 * 判断空或没数据
 */

fun String?.isNullorEmpty(): Boolean {
    return this == null || this.isEmpty()
}

/**
 * 根据布局id获取view
 */
fun getLayoutView(context: Context, layout: Int): View {
    return LayoutInflater.from(context).inflate(layout, null, false)
}

/**
 * 根据bundle+flags跳转activity
 */
fun startActivity(context: Context, clazz: Class<*>, params: Bundle, flags: Int) {
    val intent = Intent(context, clazz)
    intent.putExtras(params)
    intent.flags = flags
    context.startActivity(intent)
}

/**
 * 直接跳转activity
 */
fun startActivity(context: Context, clazz: Class<*>) {
    context.startActivity(Intent(context, clazz))
}

/**
 * 根据flags跳转activity
 */
fun startActivity(context: Context, clazz: Class<*>, flags: Int) {
    val intent = Intent(context, clazz)
    intent.flags = flags
    context.startActivity(intent)
}

/**
 * 根据bundle跳转activity
 */
fun startActivity(context: Context, clazz: Class<*>, params: Bundle) {
    val intent = Intent(context, clazz)
    intent.putExtras(params)
    context.startActivity(intent)
}

/**
 * 打印日志
 */
fun log(tag: String, log: Any) {
    Log.d(tag, "=====>$log")
}

/**
 * test数据
 */
fun getData(): ArrayList<String> {
    val data = ArrayList<String>()
    data.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603705847298&di=867c2c771e35479abd650d27f2062262&imgtype=0&src=http%3A%2F%2Fpic3.58cdn.com.cn%2Fzhuanzh%2Fn_v2fdd89f12343448c48244bb75c8aaa640.jpg%3Fw%3D750%26h%3D0")
    data.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603705847298&di=867c2c771e35479abd650d27f2062262&imgtype=0&src=http%3A%2F%2Fpic3.58cdn.com.cn%2Fzhuanzh%2Fn_v2fdd89f12343448c48244bb75c8aaa640.jpg%3Fw%3D750%26h%3D0")
    return data
}


/**
 * 设置颜色
 */
fun Context.contextColor(color: Int): Int {
    return ContextCompat.getColor(this, color)
}

/**
 * drawable设置资源
 */
fun Context.contextDrawable(id: Int): Drawable {
    return ContextCompat.getDrawable(this, id)!!
}

/**
 * mmkv对象
 */
fun mmkv(): MMKV {
    return MMKV.defaultMMKV()
}


/**
 * 安装apk
 */
fun installApk(context: Context, downloadApk: String) {
    val intent = Intent(Intent.ACTION_VIEW)
    val file = File(downloadApk)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        val uri =
            FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    } else {
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        val uri = Uri.fromFile(file)
        intent.setDataAndType(uri, "application/vnd.android.package-archive")
    }
    context.startActivity(intent)
}

fun installApkCompetence(context: Context, fileName: String) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val hasInstallPermission = context.packageManager.canRequestPackageInstalls()
        if (!hasInstallPermission) {
            val packageURI: Uri = Uri.parse("package:" + context.packageName)
            val intent =
                Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI)
            (context as Activity).startActivityForResult(intent, 1000)
        } else {
            installApk(context, updatePath(context, fileName))
        }
    } else {
        installApk(context, updatePath(context, fileName))
    }
}

/**
 * 更新保存地址
 */
fun updatePath(context: Context, fileName: String): String {
    return context.externalCacheDir?.absolutePath + File.separator + fileName
}

// 新建 Extras 类作为被委托类
class Extras<out T>(private val key: String, private val default: T) {
    // 重载取值操作符
    operator fun getValue(thisRef: Any, kProperty: KProperty<*>): T? =
        when (thisRef) {
            // 获取传递给 Activity 的参数
            is Activity -> {
                thisRef.intent?.extras?.get(key) as? T ?: default
            }
            // 获取传递给 Fragment 的参数
            is Fragment -> {
                thisRef.arguments?.get(key) as? T ?: default
            }
            else -> default
        }
}

fun AppCompatActivity.updateApp() {

}